package com.chen.authority.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.chen.authority.common.constant.SysConstant;
import com.chen.authority.common.response.MultiResponse;
import com.chen.authority.common.response.Response;
import com.chen.authority.common.response.SingleResponse;
import com.chen.authority.common.util.SaTokenUtil;
import com.chen.authority.model.dto.LoginDto;
import com.chen.authority.model.dto.ResetPwdDto;
import com.chen.authority.model.vo.RouterVo;
import com.chen.authority.model.vo.UserVo;
import com.chen.authority.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * 认证鉴权相关操作
 *
 * @author chengy
 * @date 2022/11/24
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "登录验证 LoginController")
public class LoginController {

    private final LoginService loginService;
    private final RoleService roleService;
    private final MenuService menuService;
    private final DepartmentService departmentService;
    private final PostService postService;

    @GetMapping("/captcha")
    @ApiOperation("生成图片验证码")
    public SingleResponse<Map<Object, Object>> picCaptcha() {
        return loginService.createPicCaptcha();
    }

    @PostMapping("/captcha")
    @ApiOperation("发送邮箱验证码")
    public Response emailCaptcha(String email) {
        return loginService.sendEmailCaptcha(email);
    }

    @PutMapping("/password")
    @ApiOperation("重置密码")
    public Response resetPwd(@Valid @RequestBody ResetPwdDto dto) {
        return loginService.resetPwdByCondition(dto);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Response login(@Valid @RequestBody LoginDto dto) {
        return loginService.userLogin(dto);
    }

    @GetMapping("/detail")
    @ApiOperation("获取当前登录用户详情")
    public SingleResponse<UserVo> detail() {
        UserVo user = SaTokenUtil.getLoginUser();
        user.setRoles(roleService.findRolesByUserId(user.getId()));
        user.setMenuPermissions(menuService.findMenuPermissionsByUserId(user.getId()));
        user.setDepartmentName(departmentService.getById(user.getDepartmentId()).getName());
        user.setPostName(postService.getById(user.getPostId()).getName());
        StpUtil.getTokenSession().set(SysConstant.LOGIN_USER, user);
        return SingleResponse.success(user);
    }

    @GetMapping("/router")
    @ApiOperation("获取当前登录用户路由")
    public MultiResponse<RouterVo> findRouters() {
        return MultiResponse.success(menuService.findRoutersByLoginUser());
    }

    @DeleteMapping("/logout")
    @ApiOperation("退出登录")
    public Response logout() {
        StpUtil.logout();
        return Response.success();
    }

}
